<div class="category-selector">
    <!-- 搜索框 -->
    <div class="mb-2">
        <input type="text" id="category-search" class="form-control form-control-sm" placeholder="搜索分类...">
    </div>
    
    <!-- 已选分类标签显示区域 -->
    <div class="selected-categories mb-2">
        <div class="selected-tags" id="selected-category-tags">
            <!-- 已选分类标签将在这里动态显示 -->
        </div>
    </div>
    
    <!-- 分类树形结构 -->
    <div class="category-tree" id="category-tree" style="max-height: 300px; overflow-y: auto; border: 1px solid #ddd; border-radius: 0.25rem; padding: 0.5rem;">
        {{ tree_html|safe }}
    </div>
</div>

<script>
// 分类搜索功能
document.getElementById('category-search').addEventListener('input', function(e) {
    const searchTerm = e.target.value.toLowerCase();
    const treeItems = document.querySelectorAll('.category-item');
    
    treeItems.forEach(item => {
        const categoryName = item.querySelector('.category-label').textContent.toLowerCase();
        
        if (searchTerm === '') {
            // 如果搜索词为空，显示所有项目，但保持折叠状态
            item.style.display = '';
            const parentId = item.getAttribute('data-parent');
            if (parentId !== '0') {  // 非根节点默认隐藏
                const parentExpanded = document.querySelector(`.category-item[data-id="${parentId}"] .category-children`);
                if (!parentExpanded || parentExpanded.style.display !== 'block') {
                    item.style.display = 'none';
                }
            }
        } else if (categoryName.includes(searchTerm)) {
            // 显示匹配的项目
            item.style.display = '';
            // 展开所有父级节点
            let parentId = item.getAttribute('data-parent');
            while (parentId && parentId !== '0') {
                const parentItem = document.querySelector(`.category-item[data-id="${parentId}"]`);
                if (parentItem) {
                    parentItem.style.display = '';
                    const childrenContainer = parentItem.querySelector('.category-children');
                    if (childrenContainer) {
                        childrenContainer.style.display = 'block';
                        const toggleButton = parentItem.querySelector('.category-toggle');
                        if (toggleButton) {
                            toggleButton.textContent = '−';
                        }
                    }
                    parentId = parentItem.getAttribute('data-parent');
                } else {
                    break;
                }
            }
        } else {
            // 隐藏不匹配的项目
            item.style.display = 'none';
        }
    });
});

// 切换分类子项显示/隐藏
function toggleCategoryChildren(categoryId) {
    const childrenContainer = document.getElementById('children-' + categoryId);
    const toggleButton = document.getElementById('toggle-' + categoryId);
    
    if (childrenContainer && toggleButton) {
        if (childrenContainer.style.display === 'none' || childrenContainer.style.display === '') {
            childrenContainer.style.display = 'block';
            toggleButton.textContent = '−';
        } else {
            childrenContainer.style.display = 'none';
            toggleButton.textContent = '+';
        }
    }
}

// 处理分类选择变化
function handleCategoryChange(checkbox) {
    const categoryId = checkbox.value;
    const categoryName = checkbox.nextElementSibling.textContent.trim();
    
    if (checkbox.checked) {
        addSelectedCategoryTag(categoryId, categoryName);
    } else {
        removeSelectedCategoryTag(categoryId);
    }
}

// 添加已选分类标签
function addSelectedCategoryTag(id, name) {
    const tagContainer = document.getElementById('selected-category-tags');
    const tagExists = document.querySelector(`.category-tag[data-id="${id}"]`);
    
    if (!tagExists) {
        const tag = document.createElement('span');
        tag.className = 'badge bg-primary me-1 mb-1 category-tag';
        tag.setAttribute('data-id', id);
        tag.innerHTML = `
            ${name}
            <button type="button" class="btn-close btn-close-white ms-1" 
                    onclick="removeCategoryById(${id})" 
                    style="font-size: 0.4rem;"></button>
        `;
        tagContainer.appendChild(tag);
    }
}

// 移除已选分类标签
function removeSelectedCategoryTag(id) {
    const tag = document.querySelector(`.category-tag[data-id="${id}"]`);
    if (tag) {
        tag.remove();
    }
}

// 根据ID移除分类
function removeCategoryById(id) {
    const checkbox = document.querySelector(`input[value="${id}"]`);
    if (checkbox) {
        checkbox.checked = false;
        removeSelectedCategoryTag(id);
    }
}

// 页面加载完成后初始化已选分类标签
document.addEventListener('DOMContentLoaded', function() {
    const checkedBoxes = document.querySelectorAll('input[name="{{ name }}"]:checked');
    checkedBoxes.forEach(checkbox => {
        const categoryId = checkbox.value;
        const categoryName = checkbox.nextElementSibling.textContent.trim();
        addSelectedCategoryTag(categoryId, categoryName);
    });
});
</script>